class StoreCustomer < ApplicationRecord
  attr_accessor :password, :password_confirmation

  has_many :orders, class_name: "StoreOrder"
  has_many :products, class_name: "StoreProduct"

  validates :password, confirmation: true, unless: ->(customer){customer.password.blank?}
  validates :login_name, presence: true, uniqueness: { message: "已经存在!" }
  before_create :encrypt_password

  scope :by_ids, ->(ids) { where(id: ids) }

  def encrypt_with_salt(txt, salt)
    Digest::SHA256.hexdigest("#{salt}#{txt}")
  end

  def password_connection?
    self.encrypted_password == self.encrypt_with_salt(self.password, self.salt)
  end

  def reset_password!(new_password, pass_confirmation)
    reset_password(new_password, pass_confirmation)
    self.save
  end

  private
  def encrypt_password
    self.salt = Digest::MD5.hexdigest("--#{Time.now.to_i}--")
    self.encrypted_password = self.encrypt_with_salt(self.password, self.salt)
  end

  def password_required?
   !password.nil? || !password_confirmation.nil?
  end

  def reset_password(new_password, pass_confirmation)
    self.password = new_password
    self.password_confirmation = pass_confirmation
    encrypt_password
  end
end
